<template>
  <div class="system-select" @click.stop="handleSystemModal">
    <p>{{ selectValue }}</p>
    <span class="mr10"><i class="iconfont wos-to-bottom" /></span>
  </div>
  <teleport to="body">
    <ul v-if="modalVisible" class="system-select-modal" ref="modalDom" :style="modalStyle">
      <li v-for="item in list" :key="item.label" @click.stop="handleChange(item)">
        {{ item.label }}
      </li>
    </ul>
  </teleport>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useClickBlankHidden } from '@/hooks'
import { getZIndex } from '@/utils/utils'
import type { PropType } from 'vue'

interface ISystemSelectList {
  label: string
  value: string
}

const props = defineProps({
  value: {
    type: String as PropType<string>,
    required: true
  },
  list: {
    type: Array as PropType<ISystemSelectList[]>,
    required: true,
    default: () => []
  }
})

const emit = defineEmits(['change'])

useClickBlankHidden(
  () => modalDom.value,
  () => (modalVisible.value = false)
)

const modalDom = ref<HTMLElement>()
const modalVisible = ref<boolean>(false)
const modalInfo = reactive({ x: 0, y: 0, width: 0, height: 0 })
const modalStyle = computed(() => ({
  left: `${modalInfo.x}px`,
  top: `${modalInfo.y}px`,
  width: `${modalInfo.width}px`,
  zIndex: getZIndex()
}))
const selectValue = computed(() => {
  return props.list.find((item) => item.value === props.value)?.label
})

// 切换选项
const handleChange = (data: ISystemSelectList) => {
  emit('change', data.value)
  modalVisible.value = false
}

// 下拉弹窗
const handleSystemModal = (ev: MouseEvent) => {
  const target = ev.currentTarget as HTMLElement
  const { left, top, width } = target.getBoundingClientRect()
  modalInfo.x = left
  modalInfo.y = top
  modalInfo.width = width
  modalVisible.value = true
}
</script>

<style scoped lang="scss">
@import '@/assets/scss/mixin';

.system-select {
  box-sizing: border-box;
  width: 280px;
  height: 34px;
  border: 2px solid var(--task-modal-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;

  > p {
    width: 80%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
}

.system-select-modal {
  position: fixed;
  padding: 6px 0;
  display: flex;
  flex-direction: column;
  color: var(--system-modal-drag-color);
  background-color: var(--system-modal-drag-bg-color);
  border: 2px solid var(--task-modal-border-color);

  > li {
    display: flex;
    align-items: center;
    height: 30px;
    padding-left: 10px;

    &:hover {
      @include hover-model;
    }
  }
}
</style>
